/*
# Instructions for smat testing for roaring

[smat](https://github.com/mschoch/smat) is a framework that provides
state machine assisted fuzz testing.

To run the smat tests for roaring...

## Prerequisites

Go 1.18 or later (for native fuzzing support).

## Steps

1. Generate initial smat corpus:
```
go test -tags=gofuzz -run=TestGenerateSmatCorpus
```
You should see a directory `workdir` created with initial corpus files.

2. Run the fuzz test:
```
go test -run='^$' -fuzz=FuzzSmat -fuzztime=300s -timeout=60s
```

Adjust `-fuzztime` as needed for longer or shorter runs. If crashes are found,
check the test output and the reproducer files in the `workdir` directory.
You may copy the reproducers to roaring_tests.go
*/

package roaring

import (
	
	
	
	
	
	
	
	

	
	
)

// The native fuzz entry point lives in a _test.go file so the go test
// fuzz engine discovers it. See smat_fuzz_test.go for the fuzz wrapper.

var smatDebug = true

const max_value = 1048576
const max_pairs = 10

func smatLog(,  string,  ...interface{}) {
	if smatDebug {
		fmt.Print()
		fmt.Printf(, ...)
	}
}

type smatContext struct {
	pairs []*smatPair

	// Two registers, x & y.
	x int
	y int

	actions int
	// per-context last action for this fuzz worker
	lastAction *actionRecord
}

// actionRecord stores a snapshot of the state just before an action runs.
type actionRecord struct {
	Name          string
	X, Y          int
	PairSnapshots []string // base64-encoded MarshalBinary of each pair's Bitmap
}

type smatPair struct {
	bm *Bitmap
	bs *bitset.BitSet
	// parent context (nil if unknown)
	ctx *smatContext
}

// ------------------------------------------------------------------

var smatActionMap = smat.ActionMap{
	smat.ActionID('X'): smatAction("x++", smatWrap(func( *smatContext) { .x = (.x + 1) % max_value })),
	smat.ActionID('x'): smatAction("x--", smatWrap(func( *smatContext) { .x = (.x - 1 + max_value) % max_value })),
	smat.ActionID('Y'): smatAction("y++", smatWrap(func( *smatContext) { .y = (.y + 1) % max_value })),
	smat.ActionID('y'): smatAction("y--", smatWrap(func( *smatContext) { .y = (.y - 1 + max_value) % max_value })),
	smat.ActionID('*'): smatAction("x*y", smatWrap(func( *smatContext) { .x = (.x * .y) % max_value })),
	smat.ActionID('<'): smatAction("x<<", smatWrap(func( *smatContext) { .x = (.x << 1) % max_value })),

	smat.ActionID('^'): smatAction("swap", smatWrap(func( *smatContext) { .x, .y = .y, .x })),

	smat.ActionID('['): smatAction(" pushPair", smatWrap(smatPushPair)),
	smat.ActionID(']'): smatAction(" popPair", smatWrap(smatPopPair)),

	smat.ActionID('B'): smatAction(" setBit", smatWrap(smatSetBit)),
	smat.ActionID('b'): smatAction(" removeBit", smatWrap(smatRemoveBit)),

	smat.ActionID('o'): smatAction(" or", smatWrap(smatOr)),
	smat.ActionID('a'): smatAction(" and", smatWrap(smatAnd)),
	smat.ActionID('z'): smatAction(" xor", smatWrap(smatXor)),

	smat.ActionID('#'): smatAction(" cardinality", smatWrap(smatCardinality)),

	smat.ActionID('O'): smatAction(" orCardinality", smatWrap(smatOrCardinality)),
	smat.ActionID('A'): smatAction(" andCardinality", smatWrap(smatAndCardinality)),
	smat.ActionID('Z'): smatAction(" xorCardinality", smatWrap(smatXorCardinality)),

	smat.ActionID('c'): smatAction(" clear", smatWrap(smatClear)),
	smat.ActionID('r'): smatAction(" runOptimize", smatWrap(smatRunOptimize)),

	smat.ActionID('e'): smatAction(" isEmpty", smatWrap(smatIsEmpty)),

	smat.ActionID('i'): smatAction(" intersects", smatWrap(smatIntersects)),

	smat.ActionID('f'): smatAction(" flip", smatWrap(smatFlip)),

	smat.ActionID('-'): smatAction(" difference", smatWrap(smatDifference)),
}

var smatRunningPercentActions []smat.PercentAction

func init() {
	var  []int
	for  := range smatActionMap {
		 = append(, int())
	}
	slices.Sort()

	 := 100 / len(smatActionMap)
	for ,  := range  {
		smatRunningPercentActions = append(smatRunningPercentActions,
			smat.PercentAction{Percent: , Action: smat.ActionID()})
	}

	smatActionMap[smat.ActionID('S')] = smatAction("SETUP", smatSetupFunc)
	smatActionMap[smat.ActionID('T')] = smatAction("TEARDOWN", smatTeardownFunc)
}

// We only have one smat state: running.
func smatRunning( byte) smat.ActionID {
	return smat.PercentExecute(, smatRunningPercentActions...)
}

func smatAction( string,  func( smat.Context) (smat.State, error)) func(smat.Context) (smat.State, error) {
	return func( smat.Context) (smat.State, error) {
		 := .(*smatContext)

		// Snapshot all pairs' bitmaps (base64 of MarshalBinary) before action
		 := actionRecord{Name: , X: .x, Y: .y}
		if len(.pairs) > 0 {
			.PairSnapshots = make([]string, 0, len(.pairs))
			for ,  := range .pairs {
				if  == nil || .bm == nil {
					.PairSnapshots = append(.PairSnapshots, "<nil>")
					continue
				}
				,  := .bm.MarshalBinary()
				if  != nil {
					.PairSnapshots = append(.PairSnapshots, "<marshal-error:"+.Error()+">")
				} else {
					.PairSnapshots = append(.PairSnapshots, base64.StdEncoding.EncodeToString())
				}
			}
		}

		// record per-context last action (no global mutex required)
		if  != nil {
			.lastAction = &
		}

		// catch panics inside action to dump a repro and stack before re-panicking
		defer func() {
			if  := recover();  != nil {
				// best-effort: write quick repro with lastAction from context
				var  *actionRecord
				if  != nil {
					 = .lastAction
				}
				 := time.Now().UnixNano()
				 := "// Reproducer generated by smat (panic)\n"
				 += "package roaring\n\n"
				 += "import (\n\t\"encoding/base64\"\n\t\"testing\"\n)\n\n"
				 += fmt.Sprintf("func TestFuzzerPanicRepro_%d(t *testing.T) {\n", )
				// similar to checkEquals repro
				if  != nil && len(.PairSnapshots) > 0 {
					 := .X % len(.PairSnapshots)
					if  < len(.PairSnapshots) {
						 := .PairSnapshots[]
						if  != "<nil>" && !strings.HasPrefix(, "<") {
							 += fmt.Sprintf("\tb, _ := base64.StdEncoding.DecodeString(\"%s\")\n", )
							 += "\tbm := NewBitmap()\n"
							 += "\tbm.UnmarshalBinary(b)\n"
							// perform the action that caused panic
							if strings.Contains(.Name, "setBit") {
								 += fmt.Sprintf("\tbm.AddInt(%d)\n", .Y)
							} else if strings.Contains(.Name, "removeBit") {
								 += fmt.Sprintf("\tbm.Remove(%d)\n", .Y)
							} else if strings.Contains(.Name, "flip") {
								 += fmt.Sprintf("\tbm.Flip(uint64(%d), uint64(%d)+1)\n", .Y, .Y)
							} else if strings.Contains(.Name, "runOptimize") {
								 += "\tbm.RunOptimize()\n"
							} else if strings.Contains(.Name, "clear") {
								 += "\tbm.Clear()\n"
							} else if .Name == " or" {
								 := .Y % len(.PairSnapshots)
								if  < len(.PairSnapshots) {
									 := .PairSnapshots[]
									if  != "<nil>" && !strings.HasPrefix(, "<") {
										 += fmt.Sprintf("\tb2, _ := base64.StdEncoding.DecodeString(\"%s\")\n", )
										 += "\tbm2 := NewBitmap()\n"
										 += "\tbm2.UnmarshalBinary(b2)\n"
										 += "\tbm.Or(bm2)\n"
									}
								}
							} else if .Name == " and" {
								 := .Y % len(.PairSnapshots)
								if  < len(.PairSnapshots) {
									 := .PairSnapshots[]
									if  != "<nil>" && !strings.HasPrefix(, "<") {
										 += fmt.Sprintf("\tb2, _ := base64.StdEncoding.DecodeString(\"%s\")\n", )
										 += "\tbm2 := NewBitmap()\n"
										 += "\tbm2.UnmarshalBinary(b2)\n"
										 += "\tbm.And(bm2)\n"
									}
								}
							} else if .Name == " difference" {
								 := .Y % len(.PairSnapshots)
								if  < len(.PairSnapshots) {
									 := .PairSnapshots[]
									if  != "<nil>" && !strings.HasPrefix(, "<") {
										 += fmt.Sprintf("\tb2, _ := base64.StdEncoding.DecodeString(\"%s\")\n", )
										 += "\tbm2 := NewBitmap()\n"
										 += "\tbm2.UnmarshalBinary(b2)\n"
										 += "\tbm.AndNot(bm2)\n"
									}
								}
							} else if .Name == " xor" {
								 := .Y % len(.PairSnapshots)
								if  < len(.PairSnapshots) {
									 := .PairSnapshots[]
									if  != "<nil>" && !strings.HasPrefix(, "<") {
										 += fmt.Sprintf("\tb2, _ := base64.StdEncoding.DecodeString(\"%s\")\n", )
										 += "\tbm2 := NewBitmap()\n"
										 += "\tbm2.UnmarshalBinary(b2)\n"
										 += "\tbm.Xor(bm2)\n"
									}
								}
							} else {
								 += fmt.Sprintf("\t// Unhandled action: %s\n", .Name)
							}
						} else {
							 += "\t// invalid snapshot\n"
						}
					}
				}
				 += "}\n"
				if ,  := saveReproFile("smat_panic_repro", , );  == nil {
					fmt.Printf("wrote panic repro to %s\n", )
				} else {
					fmt.Printf("failed writing panic repro: %v\n", )
				}
				fmt.Printf("PANIC in action %s: %v\n", .Name, )
				fmt.Printf("stack:\n%s\n", debug.Stack())
				panic()
			}
		}()

		.actions++
		return ()
	}
}

// saveReproFile writes the given repro content to workdir/<prefix>_<ts>_test.go
// or falls back to the OS temp dir. Returns full path or error.
func saveReproFile( string,  int64,  string) (string, error) {
	// try workdir
	if  := os.MkdirAll("workdir", 0o755);  == nil {
		 := fmt.Sprintf("workdir/%s_%d_test.go", , )
		if  := os.WriteFile(, []byte(), 0o644);  == nil {
			return , nil
		}
	}
	// fallback to temp
	 := os.TempDir()
	 := fmt.Sprintf("%s_%d_test.go", , )
	 := filepath.Join(, )
	if  := os.WriteFile(, []byte(), 0o644);  == nil {
		return , nil
	} else {
		return "", 
	}
}

// Creates an smat action func based on a simple callback.
func smatWrap( func( *smatContext)) func(smat.Context) ( smat.State,  error) {
	return func( smat.Context) ( smat.State,  error) {
		 := .(*smatContext)
		()
		return smatRunning, nil
	}
}

// Invokes a callback function with the input v bounded to len(c.pairs).
func ( *smatContext) ( int,  func(*smatPair)) {
	if len(.pairs) > 0 {
		if  < 0 {
			 = -
		}
		 =  % len(.pairs)
		(.pairs[])
	}
}

// ------------------------------------------------------------------

func smatSetupFunc( smat.Context) ( smat.State,  error) {
	return smatRunning, nil
}

func smatTeardownFunc( smat.Context) ( smat.State,  error) {
	return nil, 
}

// ------------------------------------------------------------------

func smatPushPair( *smatContext) {
	if len(.pairs) >= max_pairs {
		return
	}
	 := &smatPair{
		bm:  NewBitmap(),
		bs:  bitset.New(100),
		ctx: ,
	}
	.pairs = append(.pairs, )
}

func smatPopPair( *smatContext) {
	if len(.pairs) > 0 {
		.pairs = .pairs[0 : len(.pairs)-1]
	}
}

func smatSetBit( *smatContext) {
	.withPair(.x, func( *smatPair) {
		.Validate()
		 := uint32(.y)
		.bm.AddInt(int())
		.bs.Set(uint())
		.checkEquals()
	})
}

func smatRemoveBit( *smatContext) {
	.withPair(.x, func( *smatPair) {
		.Validate()
		 := uint32(.y)
		.bm.Remove()
		.bs.Clear(uint())
		.checkEquals()
	})
}

func smatAnd( *smatContext) {
	.withPair(.x, func( *smatPair) {
		.withPair(.y, func( *smatPair) {
			.Validate()
			.Validate()
			.bm.And(.bm)
			.bs = .bs.Intersection(.bs)
			.checkEquals()
			.checkEquals()
		})
	})
}

func smatOr( *smatContext) {
	.withPair(.x, func( *smatPair) {
		.withPair(.y, func( *smatPair) {
			.Validate()
			.Validate()
			.bm.Or(.bm)
			.bs = .bs.Union(.bs)
			.checkEquals()
			.checkEquals()
		})
	})
}

func smatXor( *smatContext) {
	.withPair(.x, func( *smatPair) {
		.withPair(.y, func( *smatPair) {
			.Validate()
			.Validate()
			.bm.Xor(.bm)
			.bs = .bs.SymmetricDifference(.bs)
			.checkEquals()
			.checkEquals()
		})
	})
}

func smatAndCardinality( *smatContext) {
	.withPair(.x, func( *smatPair) {
		.withPair(.y, func( *smatPair) {
			.Validate()
			.Validate()
			 := .bm.AndCardinality(.bm)
			 := .bs.IntersectionCardinality(.bs)
			if  != uint64() {
				panic("expected same add cardinality")
			}
			.checkEquals()
			.checkEquals()
		})
	})
}

func smatOrCardinality( *smatContext) {
	.withPair(.x, func( *smatPair) {
		.withPair(.y, func( *smatPair) {
			.Validate()
			.Validate()
			 := .bm.OrCardinality(.bm)
			 := .bs.UnionCardinality(.bs)
			if  != uint64() {
				panic("expected same or cardinality")
			}
			.checkEquals()
			.checkEquals()
		})
	})
}

func smatXorCardinality( *smatContext) {
	.withPair(.x, func( *smatPair) {
		.withPair(.y, func( *smatPair) {
			.Validate()
			.Validate()
			 := .bm.OrCardinality(.bm) - .bm.AndCardinality(.bm)
			 := .bs.SymmetricDifferenceCardinality(.bs)
			if  != uint64() {
				panic("expected same xor cardinality")
			}
			.checkEquals()
			.checkEquals()
		})
	})
}

func smatRunOptimize( *smatContext) {
	.withPair(.x, func( *smatPair) {
		.Validate()
		.bm.RunOptimize()
		.checkEquals()
	})
}

func smatClear( *smatContext) {
	.withPair(.x, func( *smatPair) {
		.Validate()
		.bm.Clear()
		.bs = .bs.ClearAll()
		.checkEquals()
	})
}

func smatCardinality( *smatContext) {
	.withPair(.x, func( *smatPair) {
		 := .bm.GetCardinality()
		 := .bs.Count()
		if  != uint64() {
			panic("expected same cardinality")
		}
	})
}

func smatIsEmpty( *smatContext) {
	.withPair(.x, func( *smatPair) {
		 := .bm.IsEmpty()
		 := .bs.None()
		if  !=  {
			panic("expected same is empty")
		}
	})
}

func smatIntersects( *smatContext) {
	.withPair(.x, func( *smatPair) {
		.withPair(.y, func( *smatPair) {
			.Validate()
			.Validate()
			 := .bm.Intersects(.bm)
			 := .bs.IntersectionCardinality(.bs) > 0
			if  !=  {
				panic("intersects not equal")
			}

			.checkEquals()
			.checkEquals()
		})
	})
}

func smatFlip( *smatContext) {
	.withPair(.x, func( *smatPair) {
		.Validate()
		 := uint32(.y)
		.bm.Flip(uint64(), uint64()+1)
		.bs = .bs.Flip(uint())
		.checkEquals()
	})
}

func smatDifference( *smatContext) {
	.withPair(.x, func( *smatPair) {
		.withPair(.y, func( *smatPair) {
			.Validate()
			.Validate()
			.bm.AndNot(.bm)
			.bs = .bs.Difference(.bs)
			.checkEquals()
			.checkEquals()
		})
	})
}

func ( *smatPair) () {
	 := .bm.Validate()
	if  != nil {
		// marshal current bitmap
		var  string
		if  != nil && .bm != nil {
			if ,  := .bm.MarshalBinary();  == nil {
				 = base64.StdEncoding.EncodeToString()
			} else {
				 = "<marshal-error:" + .Error() + ">"
			}
		} else {
			 = "<nil>"
		}

		// collect last action summary from context (per-worker)
		 := "<none>"
		if  != nil && .ctx != nil {
			 := .ctx
			if .lastAction != nil {
				 = fmt.Sprintf("action=%s x=%d y=%d pairs=%d", .lastAction.Name, .lastAction.X, .lastAction.Y, len(.lastAction.PairSnapshots))
			}
		}

		// If debugging enabled, log extra info
		smatLog("ERROR: ", "bitmap invalid: %v\n", )

		// build a reproducible test snippet that reconstructs the bitmap and replays the failing action
		 := time.Now().UnixNano()
		 := fmt.Sprintf("TestFuzzerRepro_%d", )
		 := "// Reproducer generated by smat\n"
		 += "package roaring\n\n"
		 += "import (\n\t\"encoding/base64\"\n\t\"testing\"\n)\n\n"
		 += fmt.Sprintf("func %s(t *testing.T) {\n", )
		var  *actionRecord
		if  != nil && .ctx != nil {
			 = .ctx.lastAction
		}
		// use the snapshot of the modified pair
		if  != nil && len(.PairSnapshots) > 0 {
			// assume the modified pair is x % len(pairs), but since pairs are in order, and x is lastAction.X
			 := .X % len(.PairSnapshots)
			if  < len(.PairSnapshots) {
				 := .PairSnapshots[]
				if  != "<nil>" && !strings.HasPrefix(, "<") {
					 += fmt.Sprintf("\tb, _ := base64.StdEncoding.DecodeString(\"%s\")\n", )
					 += "\tbm := NewBitmap()\n"
					 += "\tbm.UnmarshalBinary(b)\n"
					 += "\tif err := bm.Validate(); err != nil {\n"
					 += "\t\tt.Errorf(\"Initial Validate failed: %v\", err)\n"
					 += "\t}\n"
					// perform the action
					if strings.Contains(.Name, "setBit") {
						 += fmt.Sprintf("\tbm.AddInt(%d)\n", .Y)
					} else if strings.Contains(.Name, "removeBit") {
						 += fmt.Sprintf("\tbm.Remove(%d)\n", .Y)
					} else if strings.Contains(.Name, "flip") {
						 += fmt.Sprintf("\tbm.Flip(uint64(%d), uint64(%d)+1)\n", .Y, .Y)
					} else if strings.Contains(.Name, "runOptimize") {
						 += "\tbm.RunOptimize()\n"
					} else if strings.Contains(.Name, "clear") {
						 += "\tbm.Clear()\n"
					} else if .Name == " or" {
						 := .Y % len(.PairSnapshots)
						if  < len(.PairSnapshots) {
							 := .PairSnapshots[]
							if  != "<nil>" && !strings.HasPrefix(, "<") {
								 += fmt.Sprintf("\tb2, _ := base64.StdEncoding.DecodeString(\"%s\")\n", )
								 += "\tbm2 := NewBitmap()\n"
								 += "\tbm2.UnmarshalBinary(b2)\n"
								 += "\tbm.Or(bm2)\n"
							}
						}
					} else if .Name == " and" {
						 := .Y % len(.PairSnapshots)
						if  < len(.PairSnapshots) {
							 := .PairSnapshots[]
							if  != "<nil>" && !strings.HasPrefix(, "<") {
								 += fmt.Sprintf("\tb2, _ := base64.StdEncoding.DecodeString(\"%s\")\n", )
								 += "\tbm2 := NewBitmap()\n"
								 += "\tbm2.UnmarshalBinary(b2)\n"
								 += "\tbm.And(bm2)\n"
							}
						}
					} else if .Name == " difference" {
						 := .Y % len(.PairSnapshots)
						if  < len(.PairSnapshots) {
							 := .PairSnapshots[]
							if  != "<nil>" && !strings.HasPrefix(, "<") {
								 += fmt.Sprintf("\tb2, _ := base64.StdEncoding.DecodeString(\"%s\")\n", )
								 += "\tbm2 := NewBitmap()\n"
								 += "\tbm2.UnmarshalBinary(b2)\n"
								 += "\tbm.AndNot(bm2)\n"
							}
						}
					} else if .Name == " xor" {
						 := .Y % len(.PairSnapshots)
						if  < len(.PairSnapshots) {
							 := .PairSnapshots[]
							if  != "<nil>" && !strings.HasPrefix(, "<") {
								 += fmt.Sprintf("\tb2, _ := base64.StdEncoding.DecodeString(\"%s\")\n", )
								 += "\tbm2 := NewBitmap()\n"
								 += "\tbm2.UnmarshalBinary(b2)\n"
								 += "\tbm.Xor(bm2)\n"
							}
						}
					} else {
						 += fmt.Sprintf("\t// Unhandled action: %s\n", .Name)
					}
					 += "\tif err := bm.Validate(); err != nil {\n"
					 += "\t\tt.Errorf(\"Validate failed: %v\", err)\n"
					 += "\t} else {\n"
					 += "\t\tt.Logf(\"Validate succeeded\")\n"
					 += "\t}\n"
				} else {
					 += "\t// invalid snapshot\n"
				}
			}
		}
		 += "}\n"

		// print the repro snippet for the developer
		fmt.Println()
		fmt.Println("=== SMAT REPRODUCER SNIPPET ===")
		if len() > 10000 {
			fmt.Println("// Reproducer too large, skipping full print")
		} else {
			fmt.Println()
		}

		// also write the repro snippet to a timestamped file in workdir/
		if len() > 10000 {
			 = "// Reproducer too large, skipping\n"
		}
		if  := os.MkdirAll("workdir", 0o755);  == nil {
			 := fmt.Sprintf("workdir/smat_repro_%d_test.go", )
			if  := os.WriteFile(, []byte(), 0o644);  == nil {
				fmt.Printf("Wrote repro to %s\n", )
			} else {
				fmt.Printf("Failed writing repro file: %v\n", )
			}
		} else {
			fmt.Printf("Failed creating workdir: %v\n", )
		}

		panic(fmt.Sprintf("[checkEquals] bitmap invalid: %v\ncurrentBase64:%s\nlastAction:%s\n", , , ))
	}
	if !.equalsBitSet(.bs, .bm) {
		panic("bitset mismatch")
	}
}

func ( *smatPair) () {
	 := .bm.Validate()
	if  != nil {
		panic(fmt.Sprintf("[Validate] bitmap invalid: %v", ))
	}
}

func ( *smatPair) ( *bitset.BitSet,  *Bitmap) bool {
	for ,  := .NextSet(0); ; ,  = .NextSet( + 1) {
		if !.ContainsInt(int()) {
			fmt.Printf("in a bitset, not b bitmap, i: %d\n", )
			fmt.Printf("  a bitset: %s\n  b bitmap: %s\n",
				.String(), .String())
			return false
		}
	}

	 := .Iterator()
	for .HasNext() {
		 := .Next()
		if !.Test(uint()) {
			fmt.Printf("in b bitmap, not a bitset, v: %d\n", )
			fmt.Printf("  a bitset: %s\n  b bitmap: %s\n",
				.String(), .String())
			return false
		}
	}

	return true
}